//
// CommandExtgensionNode.cs
//
// Author: 
//  Fredy Ramirez <framirez@pacificcoolwave.com>
//
// Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)
//
//  Creation date: Aug 9, 2011
//  Last modification: 

/*
The MIT License

Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

using System;
using Mono.Addins;
using System.IO;
using Gtk;
using Pcw.PcwTextEditor;

namespace Pcw.PcwTextEditor.ExtensionModel
{
	/// <summary>
	/// Extension node for command nodes
	/// </summary>

	//[ExtensionNode ("Command")]
	class CommandExtensionNode : TypeExtensionNode, IUserInterfaceItem
	{		
		[NodeAttribute ("label", true)] 		// Is required
		public string Label { get; set; }
		
		[NodeAttribute ("iconType")]			// defualt 'gtk'
		public string IconType { get; set; }
		
		[NodeAttribute ("icon")]				// icon name
		public string Icon { get; set; }
		
		[NodeAttribute ("toolTip")]
		public string ToolTip { get; set; }

		[NodeAttribute ("accelModKey")]			// default 'control'
		public string AccelModKey { get; set; }		
		
		[NodeAttribute ("accelKey")]
		public string AccelKey { get; set; }
			
		private ICommand cmd;
		
		public ICommand Cmd
		{
			get{return cmd;}
		}
		
		/// <summary>
		/// Returns a menu item for this command
		/// </summary>
				
		public MenuItem CreateMenuItem ()
		{			
			cmd = FindCommand();
			
			ImageMenuItem img = new ImageMenuItem(AddinManager.CurrentLocalizer.GetString(Label));
			img.Image = ImageResult();
			if (!String.IsNullOrEmpty(ToolTip))
				img.TooltipText = ToolTip;
			img.Activated += delegate {cmd.Run();};						
			
			// Get AccelKey (Ex: control + S)
			if (!String.IsNullOrEmpty(this.AccelKey)){
				Gdk.Key key = GetGdkKey(this.AccelKey.Trim());

				Gdk.ModifierType mt = Gdk.ModifierType.ControlMask;	
				if(!String.IsNullOrEmpty(AccelModKey))
				{
					if (AccelModKey.Trim() == "shift")
						mt = Gdk.ModifierType.ShiftMask;
					else if (AccelModKey.Trim() == "control")
						mt = Gdk.ModifierType.ControlMask;
					else
						throw new InvalidOperationException (AddinManager.CurrentLocalizer.GetString ("Unknown accelModKey: '{0}' - It must be 'control' or 'shift'", AccelModKey));
				}
				
				img.AddAccelerator("activate", TextEditor.MainWin.AccelGrp, new AccelKey(key, mt, AccelFlags.Visible));	
				
			}
			
			cmd.MenuObject = img;
			
			return img;
			
		}

		/// <summary>
		/// Returns a toolbar item for this command
		/// </summary>
		
		public ToolItem CreateButton ()
		{			
			cmd = FindCommand();
			
			string tp = AddinManager.CurrentLocalizer.GetString(Label);
			
			ToolButton btn = new ToolButton(ImageResult(), tp);	
			btn.UseUnderline = true;

			if (!String.IsNullOrEmpty(ToolTip))	
				tp = AddinManager.CurrentLocalizer.GetString (ToolTip);
				
			btn.TooltipText = tp;
			
			btn.Clicked += delegate {cmd.Run();};
			
			cmd.ToolObject = btn;
			
			return btn;
			
		}
				
		private ICommand FindCommand()
		{
			// Here we ensure that only one command object exists per Id
			// This way MenuItem and ToolItem will share same object.			
			
			foreach (ICommand c in TextEditor.MainWin.Commands) {
				if (c.Id.Trim() == Id.Trim())
					return c;
			}
			
			ICommand co = (ICommand) CreateInstance (typeof (ICommand));
			co.Id = Id;
			TextEditor.MainWin.Commands.Add(co);
			
			return co;
		}
		
		private Image ImageResult () 
		{
			Image img = null;
			
			if (!String.IsNullOrEmpty(Icon)) {
				
				string iType = "gtk";
				
				if (!String.IsNullOrEmpty(IconType)) 
					iType = IconType;
				
				switch(iType) 
				{
					case "gtk":
						img = new Image(Icon, IconSize.Menu);
						break;
					
					case "resource":
						img = ImageFromStream(false);
						break;
					
					case "file":
						img = ImageFromStream(true);
						break;
					
					default:
						throw new InvalidOperationException (AddinManager.CurrentLocalizer.GetString("Unknown iconType: {0}" , iType));
				}
				
			}
						
			return img;	
			
		}
		
		private Image ImageFromStream(bool isFile)
		{
			Stream s;
			Image img;
			if (isFile)
				s = File.OpenRead (Addin.GetFilePath (Icon));
			else
				s = Addin.GetResource (Icon);
			img = new Image(s);
			if (s != null)
				s.Close();
			return img;
		}
		
		private Gdk.Key GetGdkKey (string key) 
		{
			Gdk.Key k = Gdk.Key.A;
			bool found = false;
			foreach (string s in Enum.GetNames(typeof(Gdk.Key)))
			{
				if (s == key){
					k = (Gdk.Key) ((int) Enum.Parse(typeof(Gdk.Key),s));
					found = true;
					break;
				}
	  		}
			
			if (!found)
				throw new InvalidOperationException ("Could not resolve Gdk.Key for '" + key + "'");
			
			return k;
		}
	}
}
